import 'package:flutter/material.dart';
import '../../../../domain/services/directory_service.dart';
import '../../../../data/api/directories_api.dart';
import '../../../../data/models/directory.dart' as dir;
import 'directory_item.dart';
import 'file_item.dart';
import 'empty_state.dart';

/// 文件资源管理器视图组件
class FileExplorerView extends StatelessWidget {
  /// 目录服务
  final DirectoryService directoryService;

  /// 文件点击回调
  final Function(FileItem)? onFileTap;

  /// 文件菜单操作回调
  final Function(String, FileItem)? onFileMenuAction;

  /// 目录菜单操作回调
  final Function(String, dir.Directory)? onDirectoryMenuAction;

  const FileExplorerView({
    Key? key,
    required this.directoryService,
    this.onFileTap,
    this.onFileMenuAction,
    this.onDirectoryMenuAction,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final subdirectories = directoryService.subdirectories;
    final files = directoryService.files;

    if (subdirectories.isEmpty && files.isEmpty) {
      return const EmptyState();
    }

    return RefreshIndicator(
      onRefresh:
          () => directoryService.navigateToDirectory(
            directoryService.currentDirectoryId,
          ),
      child: ListView(
        padding: const EdgeInsets.all(0),
        children: [
          // 文件夹列表
          if (subdirectories.isNotEmpty) ...[
            const Padding(
              padding: EdgeInsets.only(left: 16, top: 16, bottom: 8),
              child: Text('文件夹', style: TextStyle(fontWeight: FontWeight.bold)),
            ),
            ...subdirectories.map(
              (folder) => DirectoryItem(
                directory: folder,
                onTap: () => directoryService.navigateToDirectory(folder.id),
                onMenuAction:
                    (action, directory) =>
                        _handleDirectoryMenuAction(context, action, directory),
              ),
            ),
          ],

          // 文件列表
          if (files.isNotEmpty) ...[
            const Padding(
              padding: EdgeInsets.only(left: 16, top: 16, bottom: 8),
              child: Text('文件', style: TextStyle(fontWeight: FontWeight.bold)),
            ),
            ...files.map(
              (file) => FileItemWidget(
                file: file,
                onTap: () => _handleFileTap(context, file),
                onMenuAction:
                    (action, file) =>
                        _handleFileMenuAction(context, action, file),
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 处理文件点击事件
  void _handleFileTap(BuildContext context, FileItem file) {
    if (onFileTap != null) {
      onFileTap!(file);
    } else {
      // 默认行为：显示预览即将推出提示
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('预览 ${file.fileName} 功能即将推出')));
    }
  }

  /// 处理文件菜单操作
  void _handleFileMenuAction(
    BuildContext context,
    String action,
    FileItem file,
  ) {
    if (onFileMenuAction != null) {
      onFileMenuAction!(action, file);
    } else {
      // 默认行为
      switch (action) {
        case 'delete':
          _showDeleteConfirmDialog(
            context,
            '删除文件',
            '确定要删除文件 "${file.fileName}" 吗？',
            () => directoryService.deleteFile(file.id),
          );
          break;
        case 'download':
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('下载文件功能即将推出')));
          break;
        case 'share':
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('分享文件功能即将推出')));
          break;
        case 'rename':
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('文件重命名功能即将推出')));
          break;
      }
    }
  }

  /// 处理目录菜单操作
  void _handleDirectoryMenuAction(
    BuildContext context,
    String action,
    dir.Directory directory,
  ) {
    if (onDirectoryMenuAction != null) {
      onDirectoryMenuAction!(action, directory);
    } else {
      // 默认行为
      switch (action) {
        case 'rename':
          _showRenameDialog(context, directory.id, directory.name);
          break;
        case 'delete':
          _showDeleteConfirmDialog(
            context,
            '删除文件夹',
            '确定要删除文件夹 "${directory.name}" 吗？这将删除其中的所有文件和子文件夹。',
            () => directoryService.deleteDirectory(directory.id),
          );
          break;
        case 'share':
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('分享文件夹功能即将推出')));
          break;
      }
    }
  }

  /// 显示重命名对话框
  void _showRenameDialog(
    BuildContext context,
    int directoryId,
    String currentName,
  ) {
    final TextEditingController controller = TextEditingController(
      text: currentName,
    );

    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('重命名文件夹'),
            content: TextField(
              controller: controller,
              autofocus: true,
              decoration: const InputDecoration(
                hintText: '输入新的文件夹名称',
                border: OutlineInputBorder(),
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  if (controller.text.trim().isNotEmpty &&
                      controller.text.trim() != currentName) {
                    directoryService.renameDirectory(
                      directoryId,
                      controller.text.trim(),
                    );
                  }
                },
                child: const Text('确定'),
              ),
            ],
          ),
    );
  }

  /// 显示删除确认对话框
  void _showDeleteConfirmDialog(
    BuildContext context,
    String title,
    String content,
    Function() onConfirm,
  ) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text(title),
            content: Text(content),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  onConfirm();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red.withOpacity(0.1),
                  foregroundColor: Colors.red,
                ),
                child: const Text('删除'),
              ),
            ],
          ),
    );
  }
}
